using Identity.Application.Contracts.Common;
using Identity.Application.PermissionKeyResourceIds.Commands;
using Identity.Application.PermissionKeyResourceIds.Interfaces;
using MediatR;

namespace Identity.Application.PermissionKeyResourceIds.CommandHandlers
{
    public class RemoveApiPermissionBindingCommandHandler : IRequestHandler<RemoveApiPermissionBindingCommand, Result>
    {
        private readonly IApiPermissionBindingRepository _permissionKeyResourceIdRepository;
        private readonly IUnitOfWork _unitOfWork;
        public RemoveApiPermissionBindingCommandHandler(IApiPermissionBindingRepository permissionKeyResourceIdRepository, IUnitOfWork unitOfWork)
        {
            _permissionKeyResourceIdRepository = permissionKeyResourceIdRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<Result> Handle(RemoveApiPermissionBindingCommand request, CancellationToken cancellationToken)
        {
            var apiPermission = _permissionKeyResourceIdRepository.GetByResourceId(request.resourceId);
            if (apiPermission == null) return Result.Failure("数据不存在");
            _permissionKeyResourceIdRepository.Remove(apiPermission);
            await _unitOfWork.SaveChangesAsync(cancellationToken);
            return Result.Success();
        }
    }
}